<template>
  <div class="table">
    <div class="table_top">
      <div class="table_top_L">
        <el-form :inline="true" :model="formInline" class="demo-form-inline">
          <el-form-item label="联赛名称">
            <el-input v-model="formInline.contestName" placeholder="联赛名称"></el-input>
          </el-form-item>
          <el-form-item label="审核状态">
            <el-select v-model="formInline.auditStatus" placeholder="审核状态" clearable>
              <el-option label="审核中" value="0"></el-option>
              <el-option label="审核通过" value="1"></el-option>
              <el-option label="审核失败" value="2"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="时间">
            <el-date-picker
              v-model="formInline.time"
              type="daterange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
            >
            </el-date-picker>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="inquire">查询</el-button>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="onBinding">联赛绑定</el-button>
          </el-form-item>
        </el-form>
      </div>
    </div>
    <el-table
      :data="tableData"
      width="10%"
      height="100%"
      border
      stripe
      highlight-current-row
      v-loading="listLoading"
      ref="table"
      current-row-key="id"
      row-key="id"
      key="id"
      column-key="id"
      @selection-change="selectionChange"
    >
      <el-table-column prop="id" label="联赛id" width="80"></el-table-column>
      <el-table-column prop="contestBeginTime" label="联赛开始时间"></el-table-column>
      <el-table-column prop="contestName" label="联赛名称"></el-table-column>
      <el-table-column prop="createUserName" label="创建人名称"></el-table-column>
      <el-table-column prop="phone" label="创建人手机号"></el-table-column>
      <el-table-column prop="tournamentNum" label="比赛次数"></el-table-column>
      <el-table-column label="编辑">
        <template slot-scope="scope">
          <el-button type="link" @click="updateCi(scope.row)">修改</el-button>
        </template>
      </el-table-column>
      <el-table-column prop="auditStatus" label="审核状态" width="100">
        <template v-slot:default="{ row }">
          <el-tag :type="row.auditStatus == 0 ? 'info' : row.auditStatus == 1 ? 'success' : row.auditStatus == 2 ? 'danger' : 'info'">
            {{ row.auditStatus == 0 ? '审核中' : row.auditStatus == 1 ? '审核通过' : row.auditStatus == 2 ? '审核失败' : '--' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="300">
        <template slot-scope="scope">
          <el-button v-if="scope.row.auditStatus == 0" @click="del('通过', scope.row.id, scope.row)" type="success" plain size="small">
            通过
          </el-button>
          <el-button v-if="scope.row.auditStatus == 0" type="danger" plain size="small" @click="del('不通过', scope.row.id, scope.row)">
            不通过
          </el-button>

          <el-button type="info" plain size="small" @click="openUploadPhotoDialog(scope.row.id)">
            大屏轮播图
          </el-button>
          <!-- <el-button plain size="small" @click="onBinding(scope.row.id)">
            绑定
          </el-button> -->
        </template>
      </el-table-column>
    </el-table>

    <!-- 绑定弹窗 -->
    <el-dialog :visible.sync="bindVisible" title="绑定赛事" @close="onCloseBind" @opened="dialogOpened" width="80%">
      <!-- :inline="true" -->
      <div style="display: flex;justify-content: space-between;">
        <div style="width: 45%;">
          <div>联赛分组</div>
          <div>
            <el-table :data="groupList" style="width: 100%" max-height="500" @row-click="viewGroupDetail" v-loading="groupListLoading">
              <el-table-column prop="groupName" label="分组名称"></el-table-column>
              <el-table-column label="分组logo" align="center">
                <template slot-scope="scope">
                  <el-image :src="scope.row.groupLogo" style="width: 50px; height: 50px;"></el-image>
                </template>
              </el-table-column>
              <el-table-column label="操作" width="150" align="center">
                <template slot-scope="scope">
                  <el-button type="primary" size="mini" @click.stop="viewGroupDetail(scope.row)">查看</el-button>
                  <el-button type="danger" size="mini" @click.stop="deleteGroup(scope.$index)">删除</el-button>
                </template>
              </el-table-column>
            </el-table>
            <div style="margin-top: 10px; display: flex; justify-content: space-between; align-items: center;">
              <el-button type="primary" @click="openAddGroupDialog">新增分组</el-button>
              <el-pagination
                @current-change="handleGroupPageChange"
                :current-page="groupPageNum"
                :page-size="groupPageSize"
                layout="prev, pager, next"
                :total="groupTotal"
              ></el-pagination>
            </div>
          </div>
        </div>
        <div style="width: 10px;height: auto;background-color: #eee;"></div>
        <div style="width: 45%;">
          <div v-if="selectGroup.groupName">
            分组：<span style="color: red;">{{ selectGroup.groupName || '' }}</span> 绑定联赛如下
          </div>
          <div v-else>请先点击左侧分组列表查看按钮</div>
          <div style="flex: 1;display: flex;align-items: center;">
            <el-select v-model="addContestObj.ids" placeholder="选择联赛id" clearable multiple filterable style="width: 100%;">
              <el-option v-for="option in tableData1" :key="option.value" :label="option.label" :value="option.value"></el-option>
            </el-select>
            <el-button type="primary" @click="addContestSure()">确定添加</el-button>
          </div>
          <el-table
            ref="multipleTable"
            :data="bindGameList"
            tooltip-effect="dark"
            style="width: 100%;"
            max-height="500"
            v-loading="bindLoading"
            @selection-change="handleSelectionChange"
          >
            <el-table-column prop="contestName" label="联赛名称"></el-table-column>
            <!-- <el-table-column prop="contestBeginTime" label="日期"></el-table-column>
        <el-table-column prop="area" label="地点"></el-table-column>
        <el-table-column prop="teamNum" label="参与队伍"></el-table-column> -->
            <el-table-column label="操作" width="100">
              <template slot-scope="scope">
                <el-button type="danger" plain size="small" @click="unbindGame(scope.row)">
                  移除
                </el-button>
              </template>
            </el-table-column>
          </el-table>
          <!-- <span slot="footer" class="dialog-footer">
        <el-button @click="bindVisible = !bindVisible">取 消</el-button>
        <el-button type="primary" @click="bindSure">确 定</el-button>
      </span> -->
        </div>
      </div>
    </el-dialog>

    <el-dialog :visible.sync="uploadPhotoDialogVisible" title="上传图片" @close="resetUploadPhoto">
      <el-form :model="newBanner" ref="addForm">
        <el-form-item label="图片" prop="img">
          <div v-loading="isLoading" element-loading-text="正在上传...">
            <div v-for="(url, index) in uploadUrl" :key="index">
              <img v-if="url" :src="url" style="height:100px;width:100px;margin-right:10px;" />
            </div>
            <input type="file" multiple @change="handleFileChange" ref="fileInput" />
          </div>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="closePhotoDialog">取 消</el-button>
        <el-button type="primary" @click="uploadPhotos">确 定</el-button>
      </span>
    </el-dialog>

    <el-dialog :visible.sync="updateVisible" title="修改次数" @close="onCloseUpdate">
      <el-form :model="newBanner" ref="addForm" labelWidth="100px">
        <el-form-item label="比赛次数">
          <el-input type="number" v-model="updateObj.tournamentNum"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="onCloseUpdate">取 消</el-button>
        <el-button type="primary" @click="updateSubmit">确 定</el-button>
      </span>
    </el-dialog>
    <!--    <el-dialog :visible.sync="uploadPhotoDialogVisible" title="上传图片" @close="resetUploadPhoto">-->
    <!--      <el-form :model="newBanner" ref="addForm">-->
    <!--        <el-form-item label="图片" prop="img">-->
    <!--          <div v-loading="isLoading" element-loading-text="正在上传...">-->
    <!--            <img v-if="uploadUrl" :src="uploadUrl" style="height:100px;width:100px;">-->
    <!--            <input type="file" @change="handleFileChange" ref="fileInput">-->
    <!--          </div>-->
    <!--        </el-form-item>-->
    <!--      </el-form>-->
    <!--      <span slot="footer" class="dialog-footer">-->
    <!--        <el-button @click="uploadPhotoDialogVisible = false">取 消</el-button>-->
    <!--        <el-button type="primary" @click="uploadPhotos">确 定</el-button>-->
    <!--      </span>-->
    <!--    </el-dialog>-->

    <el-dialog :visible.sync="addGroupDialogVisible" title="新增分组" @close="resetAddGroup">
      <el-form :model="newGroup" ref="groupForm" labelWidth="100px">
        <el-form-item label="分组名称" prop="groupName">
          <el-input v-model="newGroup.groupName" placeholder="输入分组名称"></el-input>
        </el-form-item>
        <el-form-item label="分组logo" prop="logo">
          <div v-loading="isGroupLogoLoading" element-loading-text="正在上传...">
            <img v-if="newGroup.logoPreview" :src="newGroup.logoPreview" style="height:100px;width:100px;" />
            <input type="file" @change="handleGroupLogoChange" ref="groupLogoInput" />
          </div>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addGroupDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitNewGroup">确 定</el-button>
      </span>
    </el-dialog>

    <div class="table_bottom">
      <el-pagination @current-change="paginationChange" small background layout="prev, pager, next" :total="total" :page-size="20">
      </el-pagination>
    </div>
  </div>
</template>

<script>
import moment from 'moment'
import {
  getContestBindingGroupList,
  deleteContestBindingGroup,
  tableInfo,
  auditStatusPost,
  uploadPhoto,
  uploadPhotos,
  // getContestBinding,
  contestBinding,
  contestUpdate,
  addContestBindingGroup,
  getContestBindingList,
  contestListDown,
  contestBindingNew
} from '../../api/table.js'

export default {
  data() {
    return {
      uploadLogo: '',
      bindForm: {
        logo: '',
        contestName: ''
      },
      //
      bingContestName: '',
      bindingData: [],
      bindVisible: false,
      bindSelection: [],
      originId: '',
      bindLoading: false,
      currentGroupId: null, // 添加当前选中的分组ID
      //
      uploadPhotoDialogVisible: false,
      fileList: [],
      tableData: [],
      listLoading: true,
      isLoading: false,
      uploadUrl: [],
      newBanner: {
        img: ''
      },
      selectRowId: 0,
      form: {
        name: '',
        region: '',
        date1: '',
        date2: '',
        delivery: false,
        type: [],
        resource: '',
        desc: ''
      },
      photoFileList: '',
      formInline: {
        contestName: '',
        auditStatus: '',
        time: ''
      },
      total: 0, // 添加总条数
      updateVisible: false,
      updateObj: {
        tournamentNum: ''
      },
      groupList: [],
      // 新增分组相关数据
      addGroupDialogVisible: false,
      isGroupLogoLoading: false,
      newGroup: {
        groupName: '',
        logo: '',
        logoPreview: ''
      },
      bindGameList: [],
      tableData1: [],
      addContestObj: {
        id: '', //分组id
        ids: [] //选中的多选联赛
      },
      selectGroup: {},
      // 分组列表相关
      groupListLoading: false,
      groupPageNum: 1,
      groupPageSize: 10,
      groupTotal: 0
    }
  },
  mounted() {
    this.tableData = this.reqData()
    this.listLoading = false
    this.getGroupList()
    this.reqData1()
  },
  methods: {
    addContestSure() {
      if (this.addContestObj.ids.length == 0) {
        this.$message.warning('请选择联赛')
        return
      }
      contestBindingNew({
        id: this.currentGroupId,
        ids: this.addContestObj.ids
      }).then(() => {
        this.$message.success('绑定成功')
        this.viewGroupDetail(this.selectGroup)
        this.addContestObj.ids = []
      })
    },
    reqData1(pageNum = 1, pageSize = 10000, query = {}) {
      const params = { pageNum, pageSize, ...query }
      contestListDown(params).then(res => {
        this.tableData1 = res.data.map(item => ({
          value: item.id,
          label: item.name // 假设 id 是数字类型
        }))
      })
    },
    viewGroupDetail(tag) {
      this.currentGroupId = tag.id // 保存当前选中的分组ID
      this.selectGroup = tag
      getContestBindingList({ id: tag.id }).then(res => {
        console.log('res11', res)
        this.bindGameList = res.data
      })
    },
    // 新增分组相关方法
    openAddGroupDialog() {
      // this.resetAddGroup()
      this.addGroupDialogVisible = true
    },
    resetAddGroup() {
      this.newGroup = {
        groupName: '',
        logo: '',
        logoPreview: ''
      }
    },
    async handleGroupLogoChange(event) {
      const file = event.target.files[0]
      if (!file) return

      this.isGroupLogoLoading = true // 开始加载

      // 使用 FileReader 来读取文件并生成预览图
      const fileReader = new FileReader()
      fileReader.onload = temp => {
        this.newGroup.logoPreview = temp.target.result
      }
      fileReader.readAsDataURL(file)

      const formData = new FormData()
      formData.append('file', file) // 'file' 为后端接收的字段名

      try {
        const response = await uploadPhoto(formData)
        this.newGroup.logo = 'https://boyubasketball.oss-cn-shanghai.aliyuncs.com/' + response.msg
        this.$message.success('图片上传成功！')
      } catch (error) {
        this.$message.error('图片上传失败！')
      } finally {
        this.isGroupLogoLoading = false // 上传完成，结束加载
      }
    },
    submitNewGroup() {
      if (!this.newGroup.groupName) {
        this.$message.warning('请输入分组名称')
        return
      }
      if (!this.newGroup.logo) {
        this.$message.warning('请上传分组logo')
        return
      }
      addContestBindingGroup({
        groupName: this.newGroup.groupName,
        groupLogo: this.newGroup.logo
      })
        .then(() => {
          this.$message.success('创建分组成功')
          this.addGroupDialogVisible = false
          this.getGroupList() // 刷新分组列表
        })
        .catch(err => {
          this.$message.error('创建分组失败：' + err.message)
        })
    },
    deleteGroup(tagIndex) {
      this.$confirm('确定删除该联赛分组吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        deleteContestBindingGroup({ id: this.groupList[tagIndex].id }).then(() => {
          this.$message.success('删除成功')
          this.getGroupList()
        })
      })
    },
    getGroupList() {
      this.groupListLoading = true
      getContestBindingGroupList({
        pageNum: this.groupPageNum,
        pageSize: this.groupPageSize
      })
        .then(res => {
          this.groupList = res.rows
          this.groupTotal = res.total || res.rows.length
        })
        .finally(() => {
          this.groupListLoading = false
        })
    },
    handleGroupPageChange(page) {
      this.groupPageNum = page
      this.getGroupList()
    },
    updateCi(row) {
      this.updateVisible = true
      this.updateObj = row
    },
    onCloseUpdate() {
      this.updateVisible = false
    },
    updateSubmit() {
      contestUpdate({
        id: this.updateObj.id,
        tournamentNum: Number(this.updateObj.tournamentNum)
      }).then(() => {
        this.$message.success('修改成功')
        this.updateVisible = false
        this.tableData = this.reqData() // 刷新表格数据
      })
    },
    //
    onCloseBind() {
      this.bindVisible = false
      this.bindGameList = []
      this.currentGroupId = null
      this.bindSelection = []
    },
    onBinding() {
      this.bindVisible = true
      // this.originId = id
      // this.bindLoading = true
      // getContestBinding({ id, contestName: this.bingContestName })
      //   .then(res => {
      //     this.bindingData = res.data
      //     this.bindVisible = true
      //   })
      //   .finally(() => {
      //     this.bindLoading = false
      //   })
    },
    dialogOpened() {
      // 在对话框完全打开后执行勾选操作
      for (let i = 0; i < this.bindingData.length; i++) {
        if (this.bindingData[i].contestFlag) {
          this.$refs.multipleTable.toggleRowSelection(this.bindingData[i])
        }
      }
    },
    handleSelectionChange(val) {
      console.log('val', val)
      this.bindSelection = val
    },
    bindSure() {
      contestBinding({
        id: this.originId,
        ids: this.bindSelection.map(item => item.id),
        logo: this.bindForm.logo,
        groupName: this.bindForm.groupName
      }).then(() => {
        this.$message.success('绑定成功')
        this.bindVisible = false
      })
    },
    async handleLogoChange(event) {
      const file = event.target.files[0]
      if (!file) return
      this.isLoading = true // 开始加载
      // 使用 FileReader 来读取文件并生成预览图
      const fileReader = new FileReader()
      fileReader.onload = temp => {
        this.uploadLogo = temp.target.result
      }
      fileReader.readAsDataURL(file)
      const formData = new FormData()
      formData.append('file', file) // 'file' 为后端接收的字段名
      try {
        const response = await uploadPhoto(formData)
        console.log(JSON.stringify(response))
        this.bindForm.logo = response.msg
        this.$message.success('图片上传成功！')
      } catch (error) {
        this.$message.error('图片上传失败！')
      } finally {
        this.isLoading = false // 上传完成，结束加载
      }
    },
    //
    async handleFileChange(event) {
      const file = event.target.files[0]
      if (!file) return

      this.isLoading = true // 开始加载

      // 使用 FileReader 来读取文件并生成预览图
      const fileReader = new FileReader()
      fileReader.onload = e => {
        this.uploadUrl.push(e.target.result) // 添加文件的base64 URL
      }
      fileReader.readAsDataURL(file)

      const formData = new FormData()
      formData.append('file', file) // 'file' 为后端接收的字段名

      try {
        const response = await uploadPhoto(formData)
        console.log(response)
        if (this.photoFileList === '') {
          this.photoFileList += response.msg
        } else {
          this.photoFileList = this.photoFileList + ',' + response.msg
        }
        console.log('this.photoFileList:' + this.photoFileList)
        this.newBanner.img = response.msg
        this.$message.success('图片上传成功！')
      } catch (error) {
        this.$message.error('图片上传失败！')
      } finally {
        this.isLoading = false // 上传完成，结束加载
      }
    },

    openUploadPhotoDialog(rowId) {
      this.uploadPhotoDialogVisible = true
      this.selectRowId = rowId
    },

    closePhotoDialog() {
      this.uploadPhotoDialogVisible = false
      this.photoFileList = ''
      this.newBanner.img = ''
      this.uploadUrl = []
    },

    resetUploadPhoto() {
      this.photoFileList = ''
      this.newBanner.img = ''
      this.uploadUrl = []
    },

    async uploadPhotos() {
      // 处理上传成功的逻辑
      let params = {
        id: this.selectRowId,
        banner: this.photoFileList
      }
      const resp = await uploadPhotos(params)
      console.log('上传轮播图：' + resp)
      this.uploadPhotoDialogVisible = false
      this.newBanner.img = ''
    },

    inquire() {
      // 获取开始时间和结束时间
      const [startTime, endTime] = this.formInline.time || []
      // 使用 Moment.js 将 Date 对象转换为 Moment.js 实例
      const formattedStartTime = startTime ? moment(startTime).format('YYYY-MM-DD') : ''
      const formattedEndTime = endTime ? moment(endTime).format('YYYY-MM-DD') : ''

      // 调用表格数据接口，传入查询参数
      this.reqData(1, 20, {
        contestName: this.formInline.contestName,
        auditStatus: this.formInline.auditStatus,
        startTime: formattedStartTime,
        endTime: formattedEndTime
      })
    },
    selectionChange(selection) {
      this.selectionLength = selection.length
    },
    handleClick(row) {
      this.dialogTitle = row ? '修改' : '新增'
      this.dialogFormVisible = true
    },
    // 分切改变，返回页码
    paginationChange(page) {
      this.listLoading = true
      this.reqData(page, 20, this.formInline) // 传入当前页码和每页显示的数据量
      this.$nextTick(() => {
        this.listLoading = false
        this.$refs.table.bodyWrapper.scrollTop = 0
      })
    },
    // 请求
    reqData(pageNum = 1, pageSize = 20, query = {}) {
      const params = { pageNum, pageSize, ...query }
      tableInfo(params).then(res => {
        this.tableData = res.rows
        this.total = res.total // 设置总条数
      })
    },
    del(actionType, id, row) {
      const auditStatus = actionType === '通过' ? 1 : 2 // 1 for pass, 2 for fail
      const data = {
        id: id,
        auditStatus: auditStatus
      }
      let that = this
      this.$confirm(`比赛状态更改为${auditStatus === 1 ? '审核通过' : '审核失败'}, 是否继续?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          auditStatusPost(data).then(res => {
            console.log(res, 'res=======----')
            that.$message({
              type: 'success',
              message: `状态更改为${auditStatus === 1 ? '审核通过' : '审核失败'}成功!`
            })
            that.tableData = that.reqData() // 刷新表格数据
            if (actionType === '通过') {
              that.$message.success('请修改比赛次数')
              setTimeout(() => {
                that.updateCi(row)
              }, 1000)
            }
          })
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消'
          })
        })
    },
    unbindGame(row) {
      this.$confirm(`确定移除联赛 "${row.contestName}" 吗？`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          if (this.currentGroupId) {
            contestBindingNew({
              id: this.currentGroupId,
              ids: this.bindGameList.filter(item => item.id !== row.id).map(item => item.id)
            })
              .then(() => {
                this.$message.success('移除成功')
                // 从列表中移除该联赛
                // this.bindGameList = this.bindGameList.filter(item => item.id !== row.id)
                this.viewGroupDetail(this.selectGroup)
              })
              .catch(err => {
                this.$message.error('移除失败：' + (err.message || '未知错误'))
              })
          } else {
            this.$message.error('无法确定当前分组')
          }
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消'
          })
        })
    }
  }
}
</script>

<style lang="scss" scoped>
.table {
  display: flex;
  flex-flow: column;
  box-sizing: border-box;

  .table_top {
    display: flex;
    justify-content: space-between;
    padding-bottom: 10px;

    .table_top_L {
      text-align-last: left;
      flex: 1;
      overflow: hidden;
    }
  }

  .table_bottom {
    margin-top: 10px;
  }

  height: 100%;
}
</style>
<style>
.table .el-table {
  transition: all ease-in-out 0.3s;
}

.table .el-table td,
.table .el-table th {
  text-align: center;
}

.table .el-dialog {
  text-align: left;
}

.table .el-dialog .line {
  text-align: center;
}

.el-image-viewer__close {
  background-color: #fff;
}

/* 重新覆盖原来的样式，原来的样式是.el-drawer获取焦点时的outline */
.el-image-viewer__wrapper:focus {
  outline: none;
}
</style>
